<template>
	<view class="container">
		<tui-navigation-bar :title="textData.name" :titleSize="14" :titleLineHeight="14" :titlefontWeight="800"
			:isOpacity="false" @init="initNavigation" backgroundColor="'rgba(0,0,0,0)'" color="#000">
			<view class="tui-header-icon" :style="{ marginTop: top + 'px' }">
				<tui-icon name="arrowleft" color="#000" @click="back"></tui-icon>
			</view>
		</tui-navigation-bar>
		<view class="map-container" id="mapContainer"></view>
		<view class="address-list">
			<view v-if="!isSearch">
				<view class="search">
					<tui-input padding="14rpx 30rpx" @click="handleSearchTap" radius="26" size="24" backgroundColor="#F5F5F5"
						color="#8A9399" placeholder="搜索位置" v-model="searchKey">
						<slot name="left">
							<image style="width: 30rpx;height: 30rpx;" src="../../../../static/search-icon@2x.png">
							</image>
						</slot>
					</tui-input>
				</view>
				<scroll-view scroll-y style="height: 500rpx;">
					<view class="address-list-item" v-for="item in addressList" :key="item.id" @click="sureAddress(item)">
						<image class="location" src="../../../../static/icon_location@2x.png"></image>
						<view>
							<text class="tip-titile">{{ item.name }}</text>
							<text class="tip-address">{{ (+item.distance).toFixed(0) }}m | {{ item.address }}</text>
						</view>
					</view>
				</scroll-view>
			</view>
			<view v-else>
				<view class="search">
					<tui-input padding="14rpx 30rpx" @blur="handelSearch" @confirm="handelSearch" @input="handelSearch"
						radius="26" size="24" backgroundColor="#F5F5F5" color="#8A9399" placeholder="搜索位置" v-model="searchKey">
						<slot name="left">
							<image style="width: 30rpx;height: 30rpx;" src="../../../../static/search-icon@2x.png">
							</image>
						</slot>
					</tui-input>
				</view>
				<scroll-view scroll-y style="height: 500rpx;">
					<view class="address-list-item" v-for="item in searchAddressList" :key="item.id" @click="sureAddress(item)">
						<image class="location" src="../../../../static/icon_location@2x.png"></image>
						<view>
							<text class="tip-titile">{{ item.name }}</text>
							<text class="tip-address">{{ (+item.distance).toFixed(0) }}m | {{ item.address }}</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>
<script>
	import * as amapFile from '@/utils/amap.js';
	export default {
		data() {
			return {
				longitude: null, // 经度 
				throttleTimer: null, // 绑定到组件实例
				latitude: null, // 经度
				textData: {
					latitude: '', // 纬度
					longitude: '', // 经度
					name: '', // 名称
					address: '', // 详细地址
					businessAreaName: '', // 商圈
					province: '', // 省份
					city: '', // 城市
					district: '', // 区县
				},
				top: 0, //标题图标距离顶部距离
				marginTp: 0,
				myAmapFun: null,
				key: '661f987dcae58c7cb089e589ad3c7b18', // 高德地图key
				addressList: [], // 搜索返回的周边列表
				isSecelt: false,
				searchAddressList: [], // 搜索返回的周边列表
				activeId: -1, // 当前选中的周边id
				isSearch: false, // 是否搜索状态
				searchKey: '', // 用户搜索的内容
				map: null, // 添加map实例
				marker: null, // 添加marker实例
			};
		},
		onLoad(options) {
			this.myAmapFun = new amapFile.AMapWX({
				key: this.key
			});
			if (options.latitude) {
				this.latitude = options.latitude;
				this.longitude = options.longitude;
				// 使用nextTick确保DOM已渲染
				this.$nextTick(() => {
					this.initMap();
					this.getRegeo();
				});
			} else {
				let data = JSON.parse(options.info)
				this.textData = data
				this.latitude = data.latitude;
				this.longitude = data.longitude;
				// 使用nextTick确保DOM已渲染
				this.$nextTick(() => {
					this.initMap();
					this.getRegeo(data && data.address || '');
				});
			}
		},
		onUnload() {
			console.log('退出')
			// 清除定时器
			if (this.throttleTimer) {
				clearTimeout(this.throttleTimer)
			}
			uni.$emit('adressInfo', {
				latitude: this.textData.latitude, // 纬度
				longitude: this.textData.longitude, // 经度
				name: this.textData.name, // 名称
				poi: {
					province: this.textData.province, // 省份
					city: this.textData.city, // 市区
					district: this.textData.district, // 区域
					businessAreaName: this.textData.businessAreaName, // 商圈
				},
				address: this.textData.address, //地址 
			})
			// 销毁地图实例
			if (this.map) {
				this.map.destroy();
			}
		},
		methods: {
			initNavigation(e) {
				this.top = e.top;
				this.marginTp = e.height
			},
			back() {
				uni.$emit('adressInfo', {
					latitude: this.textData.latitude, // 纬度
					longitude: this.textData.longitude, // 经度
					name: this.textData.name, // 名称
					poi: {
						province: this.textData.province, // 省份
						city: this.textData.city, // 市区
						district: this.textData.district, // 区域
						businessAreaName: this.textData.businessAreaName, // 商圈
					},
					address: this.textData.address, //地址 
				})
				uni.navigateBack();
			},
			getRegeo(address) {
				this.myAmapFun.getRegeo({
					location: `${this.longitude},${this.latitude}`,
					success: (data) => {
						const datas = data[0]
						console.log('逆地理编码', address, datas)
						const object = datas.regeocodeData.addressComponent
						// 更新 textData
						this.textData.latitude = this.latitude
						this.textData.longitude = this.longitude
						this.searchKey = address || datas.name
						this.textData.name = address || datas.name
						this.textData.address = address || datas.name;
						this.textData.businessAreaName = datas.name
						this.textData.province = object.province;
						this.textData.city = !Array.isArray(object.city) ? object.city : '';
						this.textData.district = object.district;
						this.addressList.splice(0, this.addressList.length, ...data[0].regeocodeData.pois);
						if (this.isSecelt) {
							this.back()
						}
					},
					fail: function(info) {
						wx.showModal({
							title: info.errMsg
						});
					},
				});
			},
			// 初始化地图
			initMap() {
				try {
					const ua = navigator.userAgent.toLowerCase();
					const isWx = !ua.match(/MicroMessenger/i)
					// 检查平台
					const isApp = uni.getSystemInfoSync().platform === 'android' || uni.getSystemInfoSync().platform ===
						'ios';

					if (isApp && isWx) {
						// App 平台使用 AMapWX 原生插件
						const amapPlugin = uni.requireNativePlugin('AMapWX');

						// 创建地图
						amapPlugin.createMap({
							id: 'mapContainer',
							zoom: 14,
							center: [this.longitude, this.latitude],
							showCompass: false,
							showScale: false,
							trafficEnabled: false
						}, (res) => {
							if (res.code !== 0) {
								console.error('Map creation failed:', res);
								uni.showToast({
									title: '地图创建失败',
									icon: 'none'
								});
								return;
							}

							// 添加标记点
							amapPlugin.addMarker({
								mapId: 'mapContainer',
								markerId: 1,
								position: [this.longitude, this.latitude],
								iconPath: '/static/iconAress.png',
								width: 42,
								height: 48
							});

							// 绑定点击事件
							amapPlugin.addEventListener({
								mapId: 'mapContainer',
								eventName: 'click'
							}, (e) => {
								const {
									longitude,
									latitude
								} = e;
								this.longitude = longitude;
								this.latitude = latitude;

								// 更新标记点位置
								amapPlugin.updateMarkerPosition({
									mapId: 'mapContainer',
									markerId: 1,
									position: [longitude, latitude]
								});

								// 调用获取周边信息
								this.getRegeo();
							});

							this.map = amapPlugin;
						});
					} else {
						// H5 平台使用 JS API
						const container = document.getElementById('mapContainer');
						if (!container) {
							console.error('Map container not found');
							return;
						}

						// 使用高德地图JS API
						const map = new AMap.Map('mapContainer', {
							zoom: 14,
							center: [this.longitude, this.latitude],
							viewMode: '3D'
						});

						// 添加标记点
						const marker = new AMap.Marker({
							position: [this.longitude, this.latitude],
							icon: new AMap.Icon({
								image: '/static/iconAress.png',
								size: new AMap.Size(42, 48),
								imageSize: new AMap.Size(42, 48)
							})
						});
						map.add(marker);

						// 绑定点击事件
						map.on('click', (e) => {
							const {
								lng,
								lat
							} = e.lnglat;
							this.longitude = lng;
							this.latitude = lat;

							// 更新标记点位置
							marker.setPosition([lng, lat]);

							// 调用获取周边信息
							this.getRegeo();
						});

						this.map = map;
						this.marker = marker;
					}
				} catch (error) {
					console.error('Map initialization error:', error);
					uni.showToast({
						title: '地图初始化失败',
						icon: 'none'
					});
				}
			},
			// 用户点击地图
			handleMarkerTap(ev) {
				// 由于使用AMap，这个方法可以移除
			},
			// 用户点击下方列表选项
			sureAddress(ev, type) {
				this.activeId = ev.id;
				const [longitudeStr, latitudeStr] = ev.location.split(',');
				this.longitude = longitudeStr;
				this.latitude = latitudeStr;

				// 更新地图中心点和标记点
				// if (this.map && this.marker) {
				// 	this.map.setCenter([longitudeStr, latitudeStr]);
				// 	this.marker.setPosition([longitudeStr,latitudeStr]);
				// }

				this.isSecelt = true;
				this.getRegeo(ev.name || '');
			},
			// 用户点击搜索按钮
			handleSearchTap() {
				this.searchKey = ''; // 清空搜索内容
				this.searchAddressList = []; // 清空搜索列表
				this.isSearch = true;
			},
			// 用户点击取消按钮（搜索列表页）
			handelCancel() {
				this.searchKey = ''; // 清空搜索内容
				this.searchAddressList = []; // 清空搜索列表
				this.isSearch = false;
			},
			// 用户搜索内容
			handelSearch(ev) {
				// 验证输入并清理  
				if (this.searchKey.trim()) {
					clearTimeout(this.throttleTimer);
					this.throttleTimer = setTimeout(() => {
						this.myAmapFun.getKeywordsSearch({
							keywords: this.searchKey.trim(),
							city: '全国', // 从环境变量读取城市设置
							success: (data) => {
								if (data.length === 0) {
									uni.showModal({
										title: '提示',
										content: '没有搜索到结果',
										showCancel: false
									});
								} else {
									// 计算每个 POI 的距离
									const poisWithDistance = data.map(poi => {
										const [poiLng, poiLat] = poi.location.split(',').map(
											Number);
										return {
											...poi,
											distance: this.calculateDistance(this.longitude,
												this.latitude, poiLng, poiLat)
										};
									});
									this.searchAddressList = poisWithDistance;
								}
							},
							fail: (err) => {
								console.error('搜索失败', err);
								uni.showToast({
									title: '搜索失败，请稍后再试',
									icon: 'none'
								});
								// 提供更多用户反馈
								uni.showModal({
									title: '错误',
									content: '搜索失败，请检查网络连接或稍后再试',
									showCancel: false
								});
							}
						});
					}, 300);
				}
			},
			// 计算两个经纬度之间的直线距离（单位：米）
			calculateDistance(lng1, lat1, lng2, lat2) {
				const rad = (d) => d * Math.PI / 180;
				const R = 6378137; // 地球半径（米）
				const radLng1 = rad(lng1);
				const radLat1 = rad(lat1);
				const radLng2 = rad(lng2);
				const radLat2 = rad(lat2);
				const deltaLng = radLng2 - radLng1;
				const deltaLat = radLat2 - radLat1;
				const a = Math.sin(deltaLat / 2) ** 2 + Math.cos(radLat1) * Math.cos(radLat2) * Math.sin(deltaLng / 2) **
					2;
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				return Math.round(R * c);
			}
		}
	};
</script>
<style lang="scss" scoped>
	:deep(.uni-easyinput__placeholder-class) {
		background-color: red !important;
	}

	.tui-header-icon {
		width: 100%;
		position: fixed;
		top: 0;
		padding: 0 0 0 38rpx;
		display: flex;
		align-items: center;
		height: 32px;
		transform: translateZ(0);
		box-sizing: border-box;
	}

	.container {
		width: 100vw;
		height: 100vh;
		position: relative;
	}

	.map-container {
		width: 100%;
		height: 100vh;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 1;
	}

	.map_text {
		background: #fff;
		padding: 0 15px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	text {
		margin: 5px 0;
		display: block;
		font-size: 12px;
	}

	.h1 {
		margin: 15px 0;
		font-size: 15px;
	}

	.address-list {
		position: absolute;
		width: 630rpx;
		background: #FFFFFF;
		z-index: 99;
		bottom: 20rpx;
		left: 30rpx;
		border-radius: 24rpx 24rpx 24rpx 24rpx;
		padding: 0 30rpx;

		.address-list-item {
			border-bottom: 1px solid #F5F5F5;
			display: flex;
			align-items: flex-start;
			padding: 30rpx 0;
			justify-content: flex-start;

			.location {
				width: 28rpx;
				height: 28rpx;
				margin-right: 20rpx;
				margin-top: 14rpx;
			}
		}
	}

	.tip-titile {
		font-size: 28rpx;
		color: #333;
		font-weight: 400;
	}

	.tip-address {
		font-size: 20rpx;
		color: gray;
	}

	.search {
		padding: 30rpx 0;
	}
</style>